package com.qall.configability.prop;


import com.qall.util.FileUtil;
import com.qall.util.HttpUtil;
import com.qall.util.JSONUtil;
import org.springframework.boot.SpringApplication;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class GetConfigUtil {

    private static final String CONFIG_KEY = "configMap";
    private static final String CONFIG_PROPERTIES = "config.properties";
    private static final String USER_HONE = "user.home";
    public static final String APP_NAME = "app.name";
    private static final String NAME_SPACE = "app.name-space";
    private static final String CONFIG_URL = "app.config-server-url";
    private static final String CONFIG_SERVER = "config-server";
    private static final String NAME_SPACE_KEY = "nameSpace";
    private static final String APP_NAME_KEY = "appName";

    public static Map<String, Object> getConfig(SpringApplication application) {

        String userHome = System.getProperty(USER_HONE);
        String applicationName = System.getProperty(APP_NAME);
        Map<String, String> map = FileUtil.readFile(userHome + File.separator + applicationName + File.separator + CONFIG_PROPERTIES);
        String appName = map.get(APP_NAME);
        String nameSpace = map.get(NAME_SPACE);
        String getConfigUrl = map.get(CONFIG_URL);
        if (CONFIG_SERVER.equals(appName)) {
            return null;
        }
        Map<String, String> params = new HashMap<>();
        params.put(NAME_SPACE_KEY, nameSpace);
        params.put(APP_NAME_KEY, appName);
        String retData = HttpUtil.get(getConfigUrl, params);
        Map<String, Object> data = JSONUtil.jsonToMap(retData);
        Map<String, Object> configApp = (Map<String, Object>) data.get(CONFIG_KEY);
        return configApp;
    }
}
